<script lang="ts" setup>
import { useVbenModal } from '@vben/common-ui';
import { useVbenForm } from '#/adapter/form';
import { addPipe } from '#/api/gis/tube';
import type { AddPipeParams } from '#/api/gis/tube';
import { message } from 'ant-design-vue';
import { z } from '#/adapter/form';

const [AddModal, AddmodalApi] = useVbenModal({
});

const [BaseForm] = useVbenForm({
  commonConfig: {
    componentProps: {
      class: 'w-full',
    },
  },
  handleSubmit: onSubmit,
  layout: 'horizontal',
  schema: [
    {
      component: 'Input',
      componentProps: {
        placeholder: '请输入管线编号',
      },
      fieldName: 'pipeCode',
      label: '管线编号',
      rules:"required",
    },
    {
      component: 'Input',
      componentProps: {
        placeholder: '请输入管线名称',
      },
      fieldName: 'pipeName',
      label: '管线名称',
      rules:"required",
    },

    {
      component: 'Select',
      componentProps: {
        allowClear: true,
        filterOption: true,
        options: [
          {
            label: '油气',
            value: 0,
          },
          {
            label: '注水',
            value: 1,
          },
        ],
        placeholder: '请选择管线类型',
        showSearch: true,
      },
      fieldName: 'pipeType',
      label: '管线类型',
      rules: 'selectRequired',
    },

    {
      component: 'Input',
      componentProps: {
        placeholder: '请输入起始点经度',
      },
      fieldName: 'startPoint_longitude',
      label: '起始点经度',
      rules: z.string()
        .min(1, { message: '请输入起始点经度' })
        .refine((value) => {
          const numValue = parseFloat(value);
          return !isNaN(numValue) && numValue >= -180 && numValue <= 180;
        }, {
          message: '经度必须在 -180 到 180 之间',
        }),
    },
    {
      component: 'Input',
      componentProps: {
        placeholder: '请输入起始点纬度',
      },
      fieldName: 'startPoint_latitude',
      label: '起始点纬度',
      rules: z.string()
        .min(1, { message: '请输入起始点纬度' })
        .refine((value) => {
          const numValue = parseFloat(value);
          return !isNaN(numValue) && numValue >= -90 && numValue <= 90;
        }, {
          message: '纬度必须在 -90 到 90 之间',
        }),
    },
    {
      component: 'Input',
      componentProps: {
        placeholder: '请输入终止点经度',
      },
      fieldName: 'endPoint_longitude',
      label: '终止点经度',
      rules: z.string()
        .min(1, { message: '请输入终止点经度' })
        .refine((value) => {
          const numValue = parseFloat(value);
          return !isNaN(numValue) && numValue >= -180 && numValue <= 180;
        }, {
          message: '经度必须在 -180 到 180 之间',
        }),
    },
    {
      component: 'Input',
      componentProps: {
        placeholder: '请输入终止点纬度',
      },
      fieldName: 'endPoint_latitude',
      label: '终止点纬度',
      rules: z.string()
        .min(1, { message: '请输入终止点纬度' })
        .refine((value) => {
          const numValue = parseFloat(value);
          return !isNaN(numValue) && numValue >= -90 && numValue <= 90;
        }, {
          message: '纬度必须在 -90 到 90 之间',
        }),
    },
    {
      component: 'Input',
      componentProps: {
        placeholder: '请输入管道埋深（米）',
      },
      fieldName: 'depth',
      label: '管道埋深(米)',
      suffix: () => '米',
      rules: z.string()
        .min(1, { message: '请输入管道埋深(米)' })
        .refine((value) => {
          // 使用正则表达式校验是否为有效的数字格式
          const isValidNumber = /^-?\d+(\.\d+)?$/.test(value);
          if (!isValidNumber) {
            return false; // 如果不符合正则表达式，直接返回false
          }
          const numValue = parseFloat(value);
          return !isNaN(numValue) && numValue >= 0; // 检查是否为有效数字且大于等于0
        }, {
          message: '管道埋深必须是一个有效的数字且大于等于0',
        }),
    },
    {
      component: 'Input',
      componentProps: {
        placeholder: '请输入管道直径（米）',
      },
      fieldName: 'diameter',
      label: '管道直径(米)',
      suffix: () => '米',
      rules: z.string()
        .min(1, { message: '请输入管道直径(米)' })
        .refine((value) => {
          // 使用正则表达式校验是否为有效的数字格式
          const isValidNumber = /^-?\d+(\.\d+)?$/.test(value);
          if (!isValidNumber) {
            return false; // 如果不符合正则表达式，直接返回false
          }
          const numValue = parseFloat(value);
          return !isNaN(numValue) && numValue >= 0; // 检查是否为有效数字且大于等于0
        }, {
          message: '管道直径必须是一个有效的数字且大于等于0',
        }),
    },
    {
      component: 'Select',
      componentProps: {
        allowClear: true,
        filterOption: true,
        options: [
          {
            label: '碳钢',
            value: '碳钢',
          },
          {
            label: '耐腐蚀合金',
            value: '耐腐蚀合金',
          },
          {
            label: '非金属复合材料',
            value: '非金属复合材料',
          },
          {
            label: '复合涂层',
            value: '复合涂层',
          },
        ],
        placeholder: '请选择管线材质',
        showSearch: true,
      },
      fieldName: 'material',
      label: '管线材质',
      rules: 'selectRequired',
    },
    {
      component: 'Input',
      componentProps: {
        placeholder: '请输入压力等级',
      },
      fieldName: 'pressureRating',
      label: '压力等级',
      rules:"required"
    },
    {
      component: 'Input',
      componentProps: {
        placeholder: '请输入管线关联转油站编号',
      },
      fieldName: 'transferStationCode',
      label: '关联转油站编号',
    },
    {
      component: 'Input',
      componentProps: {
        placeholder: '请输入管线关联计量间编号',
      },
      fieldName: 'meteringStationCode',
      label: '关联计量间编号',
    },

    {
      component: 'Input',
      componentProps: {
        placeholder: '请输入备注',
      },
      fieldName: 'remark',
      label: '备注',
    },
  ],
});

// 定义一个自定义事件
const emit = defineEmits(['refreshTable']);
function onSubmit(values: Record<string, any>) {
  const params = values as AddPipeParams;
  params.startPoint = `POINT(${params.startPoint_longitude} ${params.startPoint_latitude})`;
  params.endPoint = `POINT(${params.endPoint_longitude} ${params.endPoint_latitude})`;
  params.geometry = `LINESTRING(${params.startPoint_longitude} ${params.startPoint_latitude}, ${params.endPoint_longitude} ${params.endPoint_latitude})`;
  addPipe(params).then(() => {
    AddmodalApi.close();
    message.success('添加管线成功');
    emit('refreshTable'); // 触发自定义事件
  }).catch((error) => {
    console.error('添加管线失败:', error);

  });
}
</script>

<template>
  <AddModal title="添加管线">
    <BaseForm />
    <template #prepend-footer>
    </template>
  </AddModal>
</template>
